import express, { Request, Response, Router } from 'express';
import fs from 'fs';
import path from 'path';
import { ApiResponse } from '../types/SharedTypes';
import Room from '../models/sequelize/Room';
import { LiveStreamManager } from '../LiveStreamManager';

const router: Router = express.Router();

// 相对路径：URL_config.ini（按用户要求）
 
 
router.post('/start', async (req: Request, res: Response) => {
  try {
    const { roomId } = req.body || {};
    if (!roomId || typeof roomId !== 'string') {
      const response: ApiResponse<null> = { success: false, data: null, message: '缺少 roomId 参数' };
      res.status(400).json(response); return;
    }

    await LiveStreamManager.startVideoRecording(roomId);
    const response: ApiResponse<{ roomId: string }> = { success: true, data: { roomId }, message: '录制已启动' };
    res.status(200).json(response); return;

  }catch(err){
    const e=err as Error
    const response: ApiResponse<null> = { success: false, data: null, message: `启动失败: ${e?.message || e}` };
    res.status(500).json(response);
  }
});




// 停止录制：将对应 roomId 的行注释掉
router.post('/stop', async (req: Request, res: Response) => {
  try {
    const { roomId } = req.body || {};
    if (!roomId || typeof roomId !== 'string') {
      const response: ApiResponse<null> = { success: false, data: null, message: '缺少 roomId 参数' };
      res.status(400).json(response); return;
    }

    await LiveStreamManager.handleRoomDisconnected(roomId, { code: undefined, reason: 'manual-stop' });

    const response: ApiResponse<{ roomId: string }> = { success: true, data: { roomId }, message: '停止录制成功' };
    res.status(200).json(response);
  } catch (err: any) {
    const response: ApiResponse<null> = { success: false, data: null, message: `停止失败: ${err?.message || err}` };
    res.status(500).json(response);
  }
});


 

export default router;
